package com.atguigu.juc;

import java.util.concurrent.locks.ReentrantLock;

//资源类
class TicketLock{
    int count = 50;

    // 得到Lock
    ReentrantLock reentrantLock = new ReentrantLock();

    public void sale(){
        // 开启lock
        reentrantLock.lock();
        try {
            // 获取线程得名称
            String name = Thread.currentThread().getName();
            if(count>0){
                System.out.println(name+"购买了第"+(count--)+"张票，还剩余"+count+"张票");
            }
        }finally {
            // 关闭lock
            reentrantLock.unlock();
        }
    }
}

public class ShellTicketLock {
    public static void main(String[] args) {
        // 获取资源类
        TicketLock ticket = new TicketLock();

        // 线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    ticket.sale();
                }
            }
        },"a").start();

        // 线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    ticket.sale();
                }
            }
        },"b").start();

        // 线程3
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    ticket.sale();
                }
            }
        },"c").start();
    }
}
